<?php
/**
 * Create By guaosi
 * Author guaosi
 * Date: 2017/8/24/0024
 * Time: 14:42
 */
namespace app\models;
use phpDocumentor\Reflection\Types\Self_;
use yii\db\ActiveRecord;
use Yii;
class Order extends ActiveRecord
{
    const CREATEORDER = 0;
    const PAYFAILED = 201;
    const PAYSUCCESS = 202;
    const SENDED = 220;
    const RECEIVED = 260;

    public static $status = [
        self::CREATEORDER => '待支付',
        self::PAYFAILED   => '支付失败',
        self::PAYSUCCESS  => '等待发货',
        self::SENDED      => '已发货',
        self::RECEIVED    => '订单完成',
    ];
    public static function tableName()
    {
        return "{{%order}}"; // TODO: Change the autogenerated stub
    }
    public function getOrderDetail()
    {
        return $this->hasMany(OrderDetail::className(),['orderid'=>'orderid']);
    }
    public function getUser()
    {
        return $this->hasone(User::className(),['userid'=>'userid']);
    }
    public static function makeOrderNo()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn =
            $yCode[intval(date('Y')) - 2017] . strtoupper(dechex(date('m'))) . date(
                'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
                '%02d', rand(0, 99));
        return $orderSn;
    }
    public function rules()
    {
        return [
            [['order_no','userid','address','receiver','telephone','amount','status','expressid','createtime'],'required','on'=>['add']],
            [['expressno','orderid'],'required','message'=>'快递单号不能为空','on'=>['send'],],
            [['tradno'],'required','on'=>['pay']]
        ];
    }
    public function attributeLabels()
    {
        return [
            'expressno'=>'快递单号'
        ];
    }

    public function add($data)
    {
        $this->scenario='add';
        $this->load($data);
        if($this->validate())
        {

            if($this->save(false))
            {
                return $this->attributes['orderid'];
            }
        }

        return false;
    }
    public function send($data)
    {
        $this->scenario='send';
        $this->load($data);
        if($this->validate())
        {
          return (bool)$this->updateAll(['expressno'=>$this->expressno,'status'=>220],'orderid=:oid',['oid'=>$this->orderid]);
        }
        return false;
    }
    public static function checkSend($orderid,$type)
    {
        if(empty($orderid))
        {
            Yii::$app->session->setFlash('info','订单参数错误');
            return false;
        }
        $order=self::find()->where('orderid=:oid',['oid'=>$orderid])->one();
        if(!$order)
        {
            Yii::$app->session->setFlash('info','该订单不存在');
            return false;
        }
        if($type=='send')
        {
            $status=202;
        }
        else if($type=='change')
        {
            $status=220;
        }
        if($order->status!=$status)
        {
            Yii::$app->session->setFlash('info','该订单状态不正确');
            return false;

        }
        return true;
    }
    public static function checkordermyself($orderid)
    {
        $userid=Yii::$app->user->id;
        $order=self::find()->where('orderid=:oid and userid=:uid',['oid'=>$orderid,'uid'=>$userid])->one();
        if(!$order)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    public static function onceRefund($trade_no,$refund_amount,$out_request_no)
    {
        require_once '../vendor/Alipay/pagepay/service/AlipayTradeService.php';
        require_once '../vendor/Alipay/pagepay/buildermodel/AlipayTradeRefundContentBuilder.php';
        $RequestBuilder=new \AlipayTradeRefundContentBuilder();
        $RequestBuilder->setTradeNo($trade_no);
        $RequestBuilder->setRefundAmount($refund_amount);
        $RequestBuilder->setOutRequestNo($out_request_no);
        $config=Yii::$app->params['AlipayConfig'];
        $aop = new \AlipayTradeService($config);
        /**
         * alipay.trade.refund (统一收单交易退款接口)
         * @param $builder 业务参数，使用buildmodel中的对象生成。
         * @return $response 支付宝返回的信息
         */
        $response = $aop->Refund($RequestBuilder);
        var_dump($response);
        exit();
        return $response->code=='10000'?true:false;
    }
}